<?php


namespace App\Http\Controllers\Admin\Interaction;


use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use Illuminate\Http\Request;

class RoomInteractionPlayMethodController extends BaseController
{
    /**
     * @api {get} /interaction/playmethod/list 玩法列表
     * @apiVersion 0.1.0
     * @apiName 玩法列表
     * @apiGroup 房间互动玩法管理
     * @apiParam {Int}                     page 页码（选填）
     * @apiParam {Int}                       per_page 一页行数 （选填）
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "total": 3,
     * "current_page": 1,
     * "last_page": 1,
     * "list": [
     * {
     * "id": 2,
     * "name": "name2",
     * "client_type":1,可使用的客户端 1全部 2ios 3Android（必填）
     * "status": 0,
     * "class": 0,
     * "icon": "url",
     * "sort": 1,
     * "need_level": 0,
     * "oper_type": 0,
     * "oper_link": null,
     * "banner_url": "",
     * "background_url": "",
     * "aspect_ratio": "0.000",
     * "add_time": "2021-07-16 15:33:09",
     * "update_time": "2021-07-21 15:39:43"
     * },
     * {
     * "id": 5,
     * "name": "name5",
     * "client_type":1,
     * "status": 1,
     * "class": 0,//1主播 2用户
     * "icon": "url",
     * "sort": 1,
     * "need_level": 0,//开启需要的等级
     * "oper_type": 0,//操作类型 1:无操作类型 2:H5
     * "oper_link": null,//链接 当oper_type==2时有效
     * "banner_url": "",
     * "background_url": "",
     * "aspect_ratio": "0.000",//三位小时  2位整数
     * "add_time": "2021-07-16 15:33:19",
     * "update_time": "2021-07-21 10:57:47"
     * },
     * {
     * "id": 6,
     * "name": "name6",
     * "client_type":1,
     * "status": 1,
     * "class": 0,
     * "icon": "url",
     * "sort": 1,
     * "need_level": 0,
     * "oper_type": 0,
     * "oper_link": null,
     * "banner_url": "",
     * "background_url": "",
     * "aspect_ratio": "0.000",
     * "add_time": "2021-07-16 15:33:22",
     * "update_time": "1970-01-01 08:00:00"
     * }
     * ]
     * }
     * }
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function list(Request $request)
    {
        $v = app('validator')->make($request->all(),
            [
                'page'     => 'filled|integer|gt:0',
                'per_page' => 'filled|integer|gt:0',
            ]
        );
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }
        $page = $request->input('page', 1);
        $perPage = $request->input('per_page', 20);
        $field = ['id', 'method_name as name', 'client_type', 'status', 'class', 'icon', 'sort', 'need_level', 'oper_type', 'oper_link', 'banner_url', 'background_url', 'aspect_ratio', 'add_time', 'update_time', 'room_type'];
        $list = app('model_room_interaction_play_method')
            ->orderBy('sort', 'desc')
            ->paginate($perPage, $field, '', $page)->toArray();

        foreach ($list['data'] as &$v) {
            $v['room_type'] = explode(',', $v['room_type']);
        }
        //返回值有固定格式
        $result = [
            'total'        => $list['total'] ?? 0,
            'current_page' => $list['current_page'] ?? 1,
            'last_page'    => $list['last_page'] ?? 1,
            'list'         => $list['data'],
        ];

        return Response::sendData($result);
    }

    /**
     * @api {post} /interaction/playmethod/delete 批量删除 （禁用中）
     * @apiVersion 0.1.0
     * @apiName 批量删除互动玩法
     * @apiGroup 房间互动玩法管理
     * @apiParam {String}                     ids  用","分隔（必填）
     * @apiSuccessExample 成功响应
     *          {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    //    public function delete(Request $request)
    //    {
    //
    //        $ids = $request->input('ids', null);
    //        $idArray = explode(',', $ids);
    //        if (empty($ids)) {
    //            throw new BasicException(10001);
    //        }
    //        $res = app('model_room_interaction_play_method')->destroy($idArray);
    //        if ($res == 0) {
    //            throw new BasicException(10001);
    //        }
    //        return Response::sendData(true);
    //    }

    //显示与屏蔽状态的切换

    /**
     * @api {post} /interaction/playmethod/changestatus 改变玩法显示状态
     * @apiVersion 0.1.0
     * @apiName 改变玩法显示状态
     * @apiGroup 房间互动玩法管理
     * @apiParam {Int}                     id  （必填）
     * @apiSuccessExample 成功响应
     * {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function changeStatus(Request $request)
    {
        $id = $request->input('id', null);
        if (empty($id)) {
            throw new BasicException(10001);
        }
        $model = app('model_room_interaction_play_method');
        $detail = $model->where('id', $id)->first();
        if (empty($detail)) {
            throw new BasicException(10001);
        }
        if ($detail['status'] == 0) {
            $res = $model->where('id', $id)->update(['status' => 1, 'update_time' => time()]);
        } else {
            $res = $model->where('id', $id)->update(['status' => 0, 'update_time' => time()]);
        }

        if ($res) {
            return Response::sendData(true);
        } else {
            throw new BasicException(10001);
        }
    }


    /**
     * @api {post} /interaction/playmethod/addandup 添加与修改数据
     * @apiVersion 0.1.0
     * @apiName 添加与修改数据
     * @apiGroup 房间互动玩法管理
     * @apiParam {Int}     id          有id表示修改（选填）
     * @apiParam {String}  name         玩法名称（必填）
     * @apiParam {Int}  client_type         可使用的客户端 1全部 2ios 3Android（必填）
     * @apiParam {String}  icon        图标地址（必填）
     * @apiParam {Int}     status      状态值 0屏蔽 1显示 （必填）
     * @apiParam {Int}     class        类型 1主播 2用户（必填）
     * @apiParam {Int}     sort        排序值（必填）
     * @apiParam {Int}     need_level        开启需要的等级（必填）
     * @apiParam {String}     room_type        玩法可用的玩法类型 例如1,2,3 （必填）数据从/room/type/all接口获得 自行添加一个 id：0 room_type_name：非官方房间
     * @apiParam {Int}     oper_type        操作类型 1:无操作类型 2:H5 （必填）
     * @apiParam {Int}     oper_link       链接 当oper_type==2时 必传（选填）
     * @apiParam {Int}     banner_url        轮播图地址(选填）
     * @apiParam {Int}     background_url        背景图地址（选填）
     * @apiParam {Int}     aspect_ratio        宽高比（必填）
     * @apiSuccessExample 成功响应
     *          {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function addAndUp(Request $request)
    {
        $data = $request->all();
        $va = app('validator')->make($data, [
            'name'           => 'required|string|max:64',
            'client_type'    => 'required|integer|in:1,2,3',
            'status'         => 'required|in:0,1',
            'class'          => 'required|in:1,2',
            'icon'           => 'required|string|max:255',
            'room_type'      => 'required|string|max:255',
            //todo 系统部署后要立即配置所有玩法的room_type字段
            'sort'           => 'required|integer|min:0',
            'need_level'     => 'required|integer|min:0',
            'oper_type'      => 'required|in:1,2',
            'banner_url'     => 'string|max:255',
            'background_url' => 'string|max:255',
            'aspect_ratio'   => 'required|numeric|max:99.999|min:0',
        ]);
        if ($va->fails()) {
            throw  new BasicException(10001, $va->errors()->first());
        }
        $insertData = [
            'method_name' => $data['name'],
            'client_type' => $data['client_type'],
            'status'      => $data['status'],
            'class'       => $data['class'],
            'icon'        => $data['icon'],
            'room_type'   => $data['room_type'],

            'sort'           => $data['sort'],
            'need_level'     => $data['need_level'],
            'oper_type'      => $data['oper_type'],
            'banner_url'     => $data['banner_url'] ?? '',
            'background_url' => $data['background_url'] ?? '',
            'aspect_ratio'   => $data['aspect_ratio'],
        ];
        $insertData['room_type'] = explode(',', $insertData['room_type']);
        $insertData['room_type'] = array_unique($insertData['room_type']);
        foreach ($insertData['room_type'] as $v) {
            try {
                if ((abs(floor($v)) - $v) != 0) {
                    throw  new BasicException(10001, '房间类型为正整数');
                }
            } catch (\Exception $exception) {
                throw  new BasicException(10001, '房间类型为正整数');
            }
        }
        sort($insertData['room_type']);

        $typeLen = count($insertData['room_type']);
        $realTypeLen = app('model_room_type')->whereIn('id', $insertData['room_type'])->where('is_delete', 0)->count();

        if (in_array('0', $insertData['room_type'])) {//存在非官方房间
            if ($realTypeLen != $typeLen - 1) {
                throw  new BasicException(10001, '参数异常,存在系统没有的房间类型');
            }
        } else {
            if ($realTypeLen != $typeLen) {
                throw  new BasicException(10001, '参数异常,存在系统没有的房间类型');
            }
        }
        $insertData['room_type'] = implode(',', $insertData['room_type']);
        if ($data['oper_type'] == 2) {//操作类型为h5
            $s = isset($data['oper_link']) && is_string($data['oper_link']) && strlen($data['oper_link']) > 0 && strlen($data['oper_link']) < 255;
            if (!$s) {
                throw new BasicException(10001, 'H5类型的要有链接地址,且链接符合规范');
            }
            $insertData['oper_link'] = $data['oper_link'];
        } else {
            $insertData['oper_link'] = '';
        }


        if (isset($data['id'])) {
            $insertData['update_time'] = time();
            $res = app('model_room_interaction_play_method')
                ->where('id', $data['id'])
                ->update($insertData);
        } else {
            $insertData['add_time'] = time();
            $res = app('model_room_interaction_play_method')
                ->insert($insertData);
        }
        if ($res) {
            return Response::sendData(true);
        } else {
            throw new BasicException(10001);
        }
    }

}
